package com.lottery.ruok.lottrey.retrofitModule;

import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.MyApplication;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ChangeIP {
    private static int times = 0;
    private static long timeGap = 0;
    public interface AfterIPAction{
        void doAction();
    }

    public static void checkIPs(AfterIPAction afterIPAction){
        times = 0;
        timeGap = 0;
        String[] ipArrays = BuildConfig.HOST_URL_Array;
        if(ipArrays != null){
            for(String ip: ipArrays){
                checkIP(ip, afterIPAction);
            }
        }
    }

    private static void checkIP(final String ip, final AfterIPAction afterIPAction){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(ip)
                .build();
        HttpUrl newUrl = request.url().newBuilder().host(BuildConfig.DOMAIN_URL).build();
        Request completeRequest = request.newBuilder()
                .url(newUrl)
                .build();
        Call call = client.newCall(completeRequest);
        final long timeStamp = System.currentTimeMillis();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

                setTimes(false, ip, 0, afterIPAction);
            }

            @Override
            public void onResponse(Call call, final Response response) {
                setTimes(true, ip, System.currentTimeMillis() - timeStamp, afterIPAction);
            }
        });
    }

    private static synchronized void setTimes(boolean isResponse, String ip, long timeStamp, AfterIPAction afterIPAction){//多线程一次只能进来一次
        if(BuildConfig.DEBUG){
            System.err.println("MM " + ip + " " + timeStamp);
        }
        times++;

        if(isResponse){
            if(timeGap == 0){
                timeGap = timeStamp;

                UserInfo.setQuickUrl(ip + String.format("/cn/cgi/app/0/%s/", MyApplication.UUID));
            } else {
                if(timeGap > timeStamp){
                    timeGap = timeStamp;
                    UserInfo.setQuickUrl(ip + String.format("/cn/cgi/app/0/%s/", MyApplication.UUID));
                }
            }
        } else {
            if(timeGap == 0){//防止网络不好的时候这个网址是空，至少给它赋个值
                UserInfo.setQuickUrl(ip + String.format("/cn/cgi/app/0/%s/", MyApplication.UUID));
            }
        }

        if(times == BuildConfig.HOST_URL_Array.length){
            if(afterIPAction != null){
                afterIPAction.doAction();
            }
        }
    }
}